package com.medical.blood.controller;

import com.medical.blood.entity.DeviceStatus;
import com.medical.blood.entity.DeviceSupplies;
import com.medical.blood.service.DeviceStatusService;
import com.medical.blood.service.DeviceSuppliesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/device")
public class DeviceMonitorController {

    @Autowired
    private DeviceStatusService statusService;
    @Autowired
    private DeviceSuppliesService suppliesService;

    /**
     * 设备状态上报接口（设备端调用）
     * @param status 设备状态数据
     * @return 上报结果
     */
    @PostMapping("/status/upload")
    public Map<String, Object> uploadStatus(@RequestBody DeviceStatus status) {
        Map<String, Object> res = new HashMap<>();
        try {
            boolean success = statusService.uploadStatus(status);
            res.put("success", success);
            res.put("message", success ? "状态上报成功" : "上报失败");
        } catch (Exception e) {
            res.put("success", false);
            res.put("message", e.getMessage());
        }
        return res;
    }

    /**
     * 初始化设备耗材（管理员配置阈值）
     * @param supplies 耗材配置
     * @return 初始化结果
     */
    @PostMapping("/supplies/init")
    public Map<String, Object> initSupplies(@RequestBody DeviceSupplies supplies) {
        Map<String, Object> res = new HashMap<>();
        try {
            boolean success = suppliesService.initSupplies(supplies);
            res.put("success", success);
            res.put("message", success ? "耗材配置成功" : "配置失败（设备ID已存在）");
        } catch (Exception e) {
            res.put("success", false);
            res.put("message", e.getMessage());
        }
        return res;
    }

    /**
     * 消耗耗材（采血后调用，减少针头、试管数量）
     * @param deviceId 设备ID
     * @param useNeedle 消耗针头数量
     * @param useTube 消耗试管数量
     * @return 操作结果
     */
    @PostMapping("/supplies/use")
    public Map<String, Object> useSupplies(
            @RequestParam String deviceId,
            @RequestParam int useNeedle,
            @RequestParam int useTube) {
        Map<String, Object> res = new HashMap<>();
        try {
            boolean success = suppliesService.updateSupplies(deviceId, useNeedle, useTube);
            res.put("success", success);
            res.put("message", success ? "耗材消耗记录成功" : "操作失败");
        } catch (Exception e) {
            res.put("success", false);
            res.put("message", e.getMessage());
        }
        return res;
    }
}